package com.xiguaji.tiktok.utils.jdbc;


import com.xiguaji.tiktok.utils.jdbc.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.regex.Pattern;


@Configuration
public class JdbcTemplateKit {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    private final static String SQL_SELECT = "SELECT";
    private final static String SQL_COUNT = " COUNT(*)";
    private final static String SQL_LIMIT = " LIMIT ";
    private final static Pattern ORDER_BY_PATTERN = Pattern.compile(
            "order\\s+by\\s+[^,\\s]+(\\s+asc|\\s+desc)?(\\s*,\\s*[^,\\s]+(\\s+asc|\\s+desc)?)*",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    public  <T> PageResponse<T> getPage(Class<T> clazz, int whichPage, int pageSize, String select, String sql, Object... args) {
        String totalRowSql = SQL_SELECT + SQL_COUNT + replaceOrderBy(sql);
        int totalRow = selectForTotalRow(totalRowSql, args);
        sql += new StringBuffer(SQL_LIMIT).append((whichPage - 1) * pageSize).append(",").append(pageSize).toString();
        List<T> pageList = select(clazz,select + " " + sql, args);
        PageResponse<T> page = new PageResponse<>(pageList, totalRow);
        return page;
    }

    public <T> List<T> select(Class<T> clazz,String sql, Object... args) {
        return jdbcTemplate.query(sql, args, BeanPropertyRowMapper.newInstance(clazz));
    }

    public int selectForTotalRow(String totalRowSql,Object... args){
        return jdbcTemplate.queryForObject(totalRowSql, args, Integer.class);
    }

    private String replaceOrderBy(String sql) {
        return ORDER_BY_PATTERN.matcher(sql).replaceAll("");
    }
}
